<?php
namespace app\admin\controller;

use app\common\model\GoodsCatModel;
use app\common\model\GoodsModel;
use think\Request;
use app\common\model\GoodsTypeModel;
use app\common\model\GoodsSpecModel;
use app\common\model\GoodsSpecItemModel;
use app\common\model\StoreModel;
use common\util\ArrayUtil;
use app\common\model\GoodsSpecGoodsPriceModel;
use app\common\service\GoodsSpecService;

class Goods extends Base {

    private $goodsModel = null;
    private $goodsTypeModel = null;
    /*
     * 初始化操作
     */
    public function _initialize() {
        $this->needLogin();
        $this->goodsModel = new GoodsModel();
        $this->goodsTypeModel = new GoodsTypeModel();
    }

    // 产品列表
    public function index() {
        $cates = GoodsCatModel::instance()->where('isshow', 1)->select();
        $this->assign('cates', $cates);
        return $this->fetch();
    }

    // 产品列表 | 添加
    public function add() {
        $cates = GoodsCatModel::instance()->select();
        $stores = StoreModel::instance()->where('status',1)->select(); 
        $goods_types = GoodsTypeModel::instance()->select();
        $this->assign('cates',$cates);      
        $this->assign('stores',$stores);      
        $this->assign('goods_types', $goods_types);
        
        return $this->fetch();
    }

    // 产品列表 | 编辑
    public function edit() {
        $cates = GoodsCatModel::instance()->select();
        $id = $this->request->param('id', 0);
        $stores = StoreModel::instance()->where('status',1)->select();
        $goods_types = GoodsTypeModel::instance()->select();
        $goods = GoodsModel::instance()->find($id);
        $startDate = '';
        $endDate = '';
        if ($goods['is_time_limit']) {
            $startDate = date('Y-m-d H:i', $goods['start_time']);
            $endDate = date('Y-m-d H:i', $goods['end_time']);
        } else {
            $startDate = date('Y-m-d H:i');
            $endDate = date('Y-m-d H:i');
        }
        $goods['start_date'] = $startDate;
        $goods['end_date'] = $endDate;
        $goods['online_date'] = $goods['online_time'] ? date('Y-m-d H:i', $goods['online_time']) : '';
        
        $this->assign('stores',$stores);
        $goods['pics'] = explode(',', $goods['multipic']);
        $goods['pics_json'] = json_encode($goods['pics']);
        
        //选中产品类型对应的规格表和规格项
        $goods_type_id = $goods['goods_type_id'];
        $specPrices = [];
        $allGoodsSpecs = [];
        if($goods_type_id){
            $goodsSpecs = GoodsSpecModel::instance()->where('goods_type_id',$goods_type_id)->order('order','desc')->select();
            $goodsSpecs = collection($goodsSpecs)->toArray();
            $goodsSpecIds =  ArrayUtil::getKeyValuesFromArray($goodsSpecs, 'id');
            $goodsSpecItemsMap = [];//规格项实体map
            $goodsSpecIdMap = [];//规格项目map 一个规格对应几个规格项
            if($goodsSpecIds){
                $goodsSpecItems = GoodsSpecItemModel::instance()->whereIn('goods_spec_id',$goodsSpecIds)->select();
                $goodsSpecItems = collection($goodsSpecItems)->toArray();
                $goodsSpecIdMap = ArrayUtil::group($goodsSpecItems, 'goods_spec_id');
                $goodsSpecItemsMap = ArrayUtil::array2Map($goodsSpecItems,'id');
            }
            $allGoodsSpecs = $this->_getGoodsSpecList($goodsSpecs,$goodsSpecIdMap);
            
            //规格对应的价格
            $goodsSpecPrice = GoodsSpecGoodsPriceModel::instance()->where('goods_id',$id)->select();
            $specPrices = $this->_getSpecPrices($goodsSpecPrice,$goodsSpecs,$goodsSpecItemsMap);
        }
        
        $goods['spec_prices'] = $specPrices;
        
        $this->assign('cates', $cates);
        $this->assign('goods_types', $goods_types);
        $this->assign('all_goods_specs', $allGoodsSpecs);
        $this->assign('item', $goods);
        
        
        return $this->fetch();
    }
    
    /**
     * 获取产品规格价格信息
     * @param array $goodsSpecPrice 产品规格和价格
     * @param array $goodsSpecs
     * @param array $goodsSpecItemsMap
     */
    private function _getSpecPrices($goodsSpecPrice,$goodsSpecs,$goodsSpecItemsMap){
        $result = [];
        
        foreach ($goodsSpecPrice as $vo){
            $items = [];
            $keys = explode('_', $vo['key']);
            foreach ($keys as $key){
                $items [] = ['id'=>$goodsSpecItemsMap[$key]['goods_spec_id'],'value'=>$key];
            }
            $keynames = explode(' ', $vo['key_name']);
            $keynames[] = '库存:'.$vo['store_count'];
            $result[] = [
                'item'=> json_encode(['item'=>$items,'store_count'=>$vo['store_count']]),
                'key_name'=> implode(',', $keynames),
            ];
        }
        return $result;
    }

    /**
     * 列表
     */
    public function rs() {

        // $data = GoodsModel::GoodsLists();
        if (request()->isPost()) {
            $length = 10;

            $cateMap = GoodsCatModel::instance()->column('id,catname');
            $cateMap['0'] = '-';
            $all = Request::instance()->param();

            $start = $this->request->param('start', 0);
            $draw = $this->request->param('draw', 1);
            $goodsname = $this->request->param('goodsname', '');
            $isshow = $this->request->param('isshow', 0);
            $catid = $this->request->param('catid', '');
            $stock = $this->request->param('stock', '');

            $where = [];
            if ($goodsname) {
                $where['goodsname'] = [
                    'like',
                    '%' . $goodsname . '%'
                ];
            }

            if ($isshow) {
                $where['isshow'] = $isshow;
            }

            if ($catid) {
                $where['catid'] = $catid;
            }
            if($stock != ''){
                $where['stock'] = intval($stock);
            }

            $list = GoodsModel::instance()->where($where)
                ->order('orderby', 'desc')
                ->order('id', 'desc')
                ->limit($start, $length)
                ->select();
            foreach ($list as &$item) {
                $item['cateName'] = $cateMap[$item['catid']];
            }
            $count = GoodsModel::instance()->where($where)->count();
            $data = array(
                "returnCode" => 1,
                "returnMsg" => "success!",
                'recordsTotal' => $count,
                'recordsFiltered' => $count,
                'draw' => $draw,
                'data' => $list
            );
            return json($data);
        } else {
            return json([
                "returnCode" => - 2,
                "returnMsg" => "fail!",
                "data" => ""
            ]);
        }
    }

    /**
     * 添加
     */
    public function add_or_update() {
        if (request()->isPost()) {
            $all = $this->request->param();

            $keys = [
                'multipic'=>'列表图片',
                'goodsname'=>'产品名称',
                'price'=>'价格',
                'reward'=>'奖励',
            ];
            foreach ($keys as $key =>$val){
                if(empty($all[$key])){
                    return $this->returnResult(-1,$val.'没有设置');
                }
            }

            $id = $this->request->param('id', 0);
            $orderby = $this->request->param('orderby', 50);
            $isshow = $this->request->param('isshow', 0);
            
            $start_time = $this->request->param('start_time', '');
            $end_time = $this->request->param('end_time', '');
            $online_time = $this->request->param('online_time', '');
            $catid = $this->request->param('catid', 0, 'intval');
            $goods_type_id = $this->request->param('goods_type_id', 0, 'intval');
            $is_time_limit = $this->request->param('is_time_limit', 0, 'intval');
            $attrs = $this->request->param('attr/a');
            $price = $this->request->param('price',0,'floatval');
            $stock = $this->request->param('stock',0,'intval'); 
            $attrData = [];
            if($goods_type_id){
                list($stock,$attrData) = $this->_parseAttrs($attrs,$goods_type_id,$price);
            }
            if($online_time){
                $online_time = strtotime($online_time);
            }
            
            if ($is_time_limit == 1) {
                //
                if (empty($start_time)) {
                    return $this->returnResult(-6,'限时开始时间没有设置');
                }
                if (empty($end_time)) {
                    return $this->returnResult(-6,'限时结束时间没有设置');
                }

                $start_time = strtotime($start_time);
                $end_time = strtotime($end_time);
            } else {
                $start_time = 0;
                $end_time = 0;
            }
            $rewardRate = 0.2;//奖励比例
            if($all['reward'] >= $all['price'] * $rewardRate){
                return $this->returnResult(-6,'奖励价格大于单价价格'.intval(strval($rewardRate * 100)).'%');
            }

            $data = [
                'pic' => $all['pic'],
                'multipic' => $all['multipic'],
                'goodsname' => $all['goodsname'],
                'orderby' => $orderby,
                'catid' => $catid,
                'isshow' => $isshow,
                'stock' => $stock,
                'supply_price' => $all['supply_price'],
                'price' => $all['price'],
                'reward' => $all['reward'],
                'detail' => $all['detail'],
                'addtime' => date('Y-m-d H:i:s',time()),
                'updatetime' => date('Y-m-d H:i:s',time()),
                'start_time'=>$start_time,
                'end_time'=>$end_time,
                'is_time_limit'=>$is_time_limit,
                'store_id'=>$all['store_id'],
                'goods_type_id'=>$goods_type_id,
                'online_time'=>$online_time,
                
            ];

            if ($id) {
                $data['id'] = $id;
                $res = GoodsModel::instance()->update($data);
                if ($res) {
                    if($attrData){
                        foreach ($attrData as &$v){
                            $v['goods_id'] = $id;
                        }
                        GoodsSpecGoodsPriceModel::instance()->updateByGoodsId($id,$attrData);
                    }
                    return $this->returnResult(1,'修改成功');
                } else {
                    return $this->returnResult(-2,'修改失败');
                }
            } else {
                $id = GoodsModel::instance()->insertGetId($data);
                if ($id) {
                    if($attrData){
                        //更新规格
                        foreach ($attrData as &$v){
                            $v['goods_id'] = $id;
                        }
                        GoodsSpecGoodsPriceModel::instance()->insertAll($attrData);
                    }
                    return $this->returnResult(1,'添加成功');
                } else {
                    return $this->returnResult(1,'添加失败');
                }
            }
        } else {
            return $this->returnResult(1,'get 不支持');
        }
    }
    
    /**
     * 获取产品规格信息
     * @param int $goodsType 产品类型
     * @param array $attrs 属性
     * @return array
     */
    private function _parseAttrs($attrs,$goodsTypeId,$price){
        
        if(empty($goodsTypeId) || empty($attrs)){
            return [0,[]];
        }
        
        $attrData = [];//
        $totalStoreCount = 0;//总库存
        $goodsSpecMap = GoodsSpecModel::instance()->where('goods_type_id',$goodsTypeId)->order('order','desc')->column('id,name','id');
        $goodsSpecIds = array_keys($goodsSpecMap);
        $goodsSpecItemMap = GoodsSpecItemModel::instance()->whereIn('goods_spec_id',$goodsSpecIds)->column('item','id');
        $keys = [];
        
        foreach ($attrs as $attr){
            $attr = json_decode($attr,true);
            $items = $attr['item'];
            $storeCount = $attr['store_count'];
            $key = $this->_getGoodsSpecKey($items,$goodsSpecMap);
            if(in_array($key, $keys)){
                continue;
            }
            $keys[] = $key;
            $attrData [] = [
                'key'=>$key,
                'key_name'=>$this->_getGoodsSpesKeyName($items,$goodsSpecMap,$goodsSpecItemMap),
                'store_count'=>$storeCount,
                'price'=>$price,
            ];
            $totalStoreCount += $storeCount;
        }
        
        return [$totalStoreCount,$attrData];
    }

    private function _getGoodsSpecKey($attrs,$goodsSpecMap){
        $values = [];
        foreach ($attrs as $item){
            if(empty($item)){
                continue;
            }
            $values[$item['id']] = $item['value'];
        }
        $vals = array_keys($goodsSpecMap);
        $result = [];
        foreach ($vals as $val){
            if(array_key_exists($val, $values)){
                $result[] =  $values[$val];
            }
        }
        return implode('_', $result);
    }
    
    private function _getGoodsSpesKeyName($items,$goodsSpecMap,$goodsSpecItemMap){
        $values = [];
        foreach ($items as $item){
            if(empty($item)){
                continue;
            }
            $values [$item['id']] = $goodsSpecMap[$item['id']] .':'.$goodsSpecItemMap[$item['value']];
        }
        $vals = array_keys($goodsSpecMap);
        $result = [];
        foreach ($vals as $val){
            if(array_key_exists($val, $values)){
                $result[] =  $values[$val];
            }
        }
        return implode(' ', $result);
    }
    
    
    public function online() {
        $id = $this->request->param('id');
        GoodsModel::instance()->update([
            'id' => $id,
            'isshow' => 1
        ]);
        return $this->returnResult(1, '上线成功');
    }

    public function offline() {
        $id = $this->request->param('id');
        GoodsModel::instance()->update([
            'id' => $id,
            'isshow' => 2
        ]);
        return $this->returnResult(1, '下线成功');
    }

    public function upload_orderby() {
        $id = $this->request->param('id');
        $orderby = $this->request->param('orderby');
        GoodsModel::instance()->update([
            'id' => $id,
            'orderby' => $orderby
        ]);
        return $this->returnResult(1, '更新成功');
    }

    public function upload_stock() {
        $id = $this->request->param('id');
        $orderby = $this->request->param('stock');
        GoodsModel::instance()->update([
            'id' => $id,
            'stock' => $orderby
        ]);
        return $this->returnResult(1, '更新成功');
    }

    /**
     * 产品类型表
     */
    public function goods_type() {
        return $this->fetch();
    }
    
    
    public function goods_type_add_or_update(){
        $id = $this->request->param('id',0);
        $name = $this->request->param('name','');
        $msg = '';
        if($id){
            $this->goodsTypeModel->update(['id'=>$id,'name'=>$name]);    
            $msg = '修改成功';
        }else{
            $this->goodsTypeModel->insert(['name'=>$name]);
            $msg = '添加成功';
        }
        return $this->returnResult(1,$msg);
    }
    /**
     * 产品类型列表
     */
    public function goods_type_rs(){
        
        $length = 10;
        $start = $this->request->param('start', 0);
        $draw = $this->request->param('draw', 1);
        
        $goodsTypeModel = new GoodsTypeModel();
        $items = $goodsTypeModel->limit($start,$length)->select();
        $count = $goodsTypeModel->count();
        
        return $this->returnListResult($draw, $count, $items);
    }
    
    /**
     * 根据类型获取规格列表
     */
    public function goods_spec_list(){
        $goods_type_id = $this->request->param('goods_type_id','');
        $goodsSpecs = GoodsSpecService::getGoodsSpecList($goods_type_id);
        return $this->returnResult(1,'成功',$goodsSpecs);
    }
    
    private function _getGoodsSpecList($goodsSpecs,$goodsSpecIdMap){
        
        foreach ($goodsSpecs as &$goodsSpec){
            $goodsSpecId =  $goodsSpec['id'];
            $goodsSpec['values'] = [];
            if(array_key_exists($goodsSpecId, $goodsSpecIdMap)){
                $goodsSpec['values'] = $goodsSpecIdMap[$goodsSpecId];
            }
        }
        return $goodsSpecs;
    }
    /**
     * 商品规格表
     */
    public function goods_spec(){
        $goods_type_id = $this->request->param('goods_type_id','');
        $goodsTypeModel = new GoodsTypeModel();
        $goodsTypes = $goodsTypeModel->select();
        $this->assign('goods_types',$goodsTypes);
        
        $this->assign('goods_type_id',$goods_type_id);
        return $this->fetch();
    }
    
    public function goods_spec_add_or_update(){
        $id = $this->request->param('id',0);
        $goods_type_id = $this->request->param('goods_type_id',0);
        $name = $this->request->param('name','');
        $order = $this->request->param('order',50);
        
        
        $goodsSpecModel = new GoodsSpecModel();
        $msg = '';
        if($id){
            $data = [
                'name'=>$name,
                'order'=>$order,
            ];
            $data['id'] = $id;
            $res = $goodsSpecModel->update($data);
            $msg = '更新成功';
        }else{
            $data = [
                'goods_type_id'=>$goods_type_id,
                'name'=>$name,
                'order'=>$order,
            ];
            $res = $goodsSpecModel->insert($data);
            $msg = '添加成功';
        }
        if($res){
            return $this->returnResult(1,$msg);
        }else{
            return $this->returnResult(-1,'失败');
        }
        
    }
    
    public function goods_spec_rs(){
        
        $length = 10;
        $start = $this->request->param('start', 0);
        $draw = $this->request->param('draw', 1);
        $name = $this->request->param('name', '');
        $goods_type_id = $this->request->param('goods_type_id',0);
        $where = [];
        if($name){
            $where['name'] = ['like','%'.$name.'%'];
        }
        if($goods_type_id){
            $where['goods_type_id'] = $goods_type_id;
        }
        
        $goodsSpecModel = new GoodsSpecModel();
        $goodsTypeModel = new GoodsTypeModel();
        $goodsTypeMap = $goodsTypeModel->column('name','id');
        
        $items = $goodsSpecModel->where($where)->order('order','desc')->limit($start,$length)->select();
        foreach ($items as &$item){
            $item['goods_type_name'] = $goodsTypeMap[$item['goods_type_id']];
        }
        $count = $goodsSpecModel->where($where)->count();
        
        return $this->returnListResult($draw, $count, $items);
    }
    
    public function del_goods_spec(){
        $id = $this->request->param('id',0);
        $goodsSpecModel = new GoodsSpecModel();
        $goodsSpecItemModel = new GoodsSpecItemModel();
        if($id){
            //查询有没有goods_spec_item 数据
            $count = $goodsSpecItemModel->where('goods_spec_id',$id)->count();
            if($count){
                return $this->returnResult(-1,'该商品规格还有数据没有删除');
            }
            $goodsSpecModel->where('id',$id)->delete();
            return $this->returnResult(1,'删除成功');
        }
        return $this->returnResult(-1,'id错误');
    }
    
    
    public function goods_spec_item(){
        $goods_spec_id = $this->request->param('goods_spec_id',0); 
        $goodsSpecModel = new GoodsSpecModel();
        $goodsSpecs = $goodsSpecModel->order('order','desc')->select();
        
        $goodsSpecs = collection($goodsSpecs)->toArray();
        $goodsTypeIds = ArrayUtil::getKeyValuesFromArray($goodsSpecs, 'goods_type_id');
        $goodsTypeMap = GoodsTypeModel::instance()->whereIn('id',$goodsTypeIds)->column('name','id');
        foreach ($goodsSpecs as &$item){
            $item['name']=$goodsTypeMap[$item['goods_type_id']].'-'.$item['name'];
        }
        $this->assign('goods_specs',$goodsSpecs);
        $this->assign('goods_spec_id',$goods_spec_id);
        return $this->fetch();
    }
    
    public function goods_spec_item_rs(){
        $length = 10;
        $start = $this->request->param('start', 0);
        $draw = $this->request->param('draw', 1);
        $name = $this->request->param('name', '');
        $goods_spec_id = $this->request->param('goods_spec_id',0);
        $where = [];
        if($name){
            $where['item'] = ['like','%'.$name.'%'];
        }
        if($goods_spec_id){
            $where['goods_spec_id'] = $goods_spec_id;
        }
        
        $goodsSpecModel = new GoodsSpecModel();
        $goodsSpecItemModel =new GoodsSpecItemModel();
        
        $items = $goodsSpecItemModel->where($where)->limit($start,$length)->select();
        $goodsSpecIds = ArrayUtil::getKeyValuesFromArray($items, 'goods_spec_id');
        $goodsSpecMap = $goodsSpecModel->whereIn('id',$goodsSpecIds)->column('name,goods_type_id','id');
        $goodsTypeIds = ArrayUtil::getKeyValuesFromArray(array_values($goodsSpecMap),'goods_type_id');
        $goodsTypeMap = GoodsTypeModel::instance()->whereIn('id',$goodsTypeIds)->column('name','id');
        
        foreach ($items as &$item){
            
            $item['goods_spec_name'] = $goodsSpecMap[$item['goods_spec_id']]['name'];
            $goodsTypeId = $goodsSpecMap[$item['goods_spec_id']]['goods_type_id'];
            $item['goods_type_name'] = $goodsTypeMap[$goodsTypeId];
        }
        $count = $goodsSpecItemModel->where($where)->count();
        
        return $this->returnListResult($draw, $count, $items);
    }
    
    public function goods_spec_item_add_or_update(){
        
        $id = $this->request->param('id',0);
        $goods_spec_id = $this->request->param('goods_spec_id',0);
        $name = $this->request->param('name','');
        
        $goodsSpecItemModel = new GoodsSpecItemModel();
        $msg = '';
        if($id){
            $data = [
                'item'=>$name,
            ];
            $data['id'] = $id;
            $res = $goodsSpecItemModel->update($data);
            $msg = '更新成功';
        }else{
            $data = [
                'goods_spec_id'=>$goods_spec_id,
                'item'=>$name,
            ];
            $res = $goodsSpecItemModel->insert($data);
            $msg = '添加成功';
        }
        if($res){
            return $this->returnResult(1,$msg);
        }else{
            return $this->returnResult(-1,'失败');
        }
    }
    
    /**
     * 删除goods_spec_item 数据
     */
    public function del_goods_spec_item(){
        $id = $this->request->param('id',0);
        $goodsSpecItemModel = new GoodsSpecItemModel();
        
        if($id){
            $goodsSpecItemModel->where('id',$id)->delete();
            return $this->returnResult(1,'删除成功');
        }
        return $this->returnResult(-1,'id错误');
    }
    
    
    public function store(){
        $storeModel = new StoreModel();
        $list = $storeModel->select();
        
        $this->assign('list',$list);
        return $this->fetch();
    }
    
    public function store_add_or_update() {
        $id= $this->request->param('id',0);
        $name = $this->request->param('name');
        
        $storeModel = new StoreModel();
        if($id){
            $data = [
                'id'=>$id,
                'name'=>$name,
            ];
            $res = $storeModel->update($data);
            return $this->returnResult(1,'更新成功');
        }else{
            $data = [
                'name'=>$name,
                'status'=>1,
            ];
            
            $id = $storeModel->insertGetId($data);
            return $this->returnResult(1,'添加成功');
        }
    }
    
    public function store_online(){
        $id= $this->request->param('id',0);
        $data =['id'=>$id,'status'=>1];
        $storeModel = new StoreModel();
        $res = $storeModel->update($data);
        return $this->returnResult(1,'上线成功');
    }
    
    public function  store_offline(){
        $id= $this->request->param('id',0);
        $data =['id'=>$id,'status'=>0];
        $storeModel = new StoreModel();
        $res = $storeModel->update($data);
        return $this->returnResult(1,'下线成功');
    }

}
